package fun.boomcat.luckyhe.mirai.plugin.event;

import fun.boomcat.luckyhe.mirai.plugin.bean.Reply;
import fun.boomcat.luckyhe.mirai.plugin.dbutils.ReplyListModifier;
import fun.boomcat.luckyhe.mirai.plugin.dbutils.ServeGroupListModifier;
import kotlin.coroutines.CoroutineContext;
import net.mamoe.mirai.console.command.CommandManager;
import net.mamoe.mirai.console.command.CommandSender;
import net.mamoe.mirai.console.command.CommandSenderOnMessage;
import net.mamoe.mirai.console.plugin.jvm.JavaPlugin;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.event.events.MessageEvent;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class AutoReplyMessageListenerHost extends SimpleListenerHost {
    private final JavaPlugin INSTANCE;

    @Override
    public void handleException(@NotNull CoroutineContext context, @NotNull Throwable exception) {
        super.handleException(context, exception);
    }

    public AutoReplyMessageListenerHost(JavaPlugin instance) {
        this.INSTANCE = instance;
    }

    @EventHandler
    public void onMessage(@NotNull MessageEvent event) {
        if (event.getMessage().contentToString().startsWith(CommandManager.INSTANCE.getCommandPrefix())) {

            return;
        }

        if (event instanceof GroupMessageEvent) {
//            必须为群消息

            onGroupMessage(event);
            return;
        }
    }

    public void onGroupMessage(MessageEvent event) {
        long groupId = ((GroupMessageEvent) event).getGroup().getId();
        try {
            if (!ServeGroupListModifier.checkGroup(groupId)) {
//                该群不在群服务列表
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

//        获取匹配的回复保存为replyList列表
        List<Reply> replyList = new ArrayList<>();
        String msg = event.getMessage().contentToString();
        try {
            replyList.addAll(ReplyListModifier.getCompleteMatchReplies(msg));
            replyList.addAll(ReplyListModifier.getFuzzyMatchReplies(msg));
            replyList.addAll(ReplyListModifier.getRegexMatchReplies(msg));
            replyList.addAll(ReplyListModifier.getRegexReplaceMatchReplies(msg));
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (Reply reply : replyList) {
            INSTANCE.getLogger().info("数据库查询结果：" + reply);
        }

        if (replyList.size() == 0) {
//            未查询到任何匹配回复则退出
            return;
        }

//        从匹配回复中随机抽取回复发送
        Random random = new Random();
        int i = random.nextInt(replyList.size());
        CommandSenderOnMessage<MessageEvent> from = CommandSender.from(event);
        from.sendMessage(replyList.get(i).getReply());
    }
}
